package com.powergisol.gis.timer;

import com.powergisol.gis.util.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description:删除临时文件定时器
 */
@Component
public class DelFileTimer {
    private static Logger logger = LoggerFactory.getLogger(DelFileTimer.class);

//    @Value("${file-url}")
//    private String fileUrl;

    @Scheduled(initialDelay = 6000, fixedRate = 300000)
    //@Scheduled(cron ="0 0 0 * * ?")
    public void delFile(){
        String userDir = System.getProperty("user.dir");
        userDir = userDir.substring(0,userDir.lastIndexOf(File.separator));
        recursionFile(userDir+File.separator +"serviceData"+File.separator+"temp");
    }
    private void recursionFile(String dataPath){
        File file = new File(dataPath);
        File[] files = file.listFiles();
        if(null == files){
            return ;
        }
        for (File file1 : files) {
            if (!file1.isDirectory()) {
                int days = getDay(file1.lastModified());
                if(days >= 1){
                    logger.info(new Date()+"删除文件：{}",file1.getAbsolutePath());
                    file1.delete();
                }
            }else{
                recursionFile(file1.getAbsolutePath());
            }
        }
    }

    private int getDay(long timeFrom){
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String toStr = simpleFormat.format(new Date());
        int days = 0;
        try {
            long to = simpleFormat.parse(toStr).getTime();
            days = (int) ((to - timeFrom)/(1000 * 60 * 60 * 24));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }


    public static void main(String[] args) throws ParseException {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String toStr = simpleFormat.format(new Date());
        long from = simpleFormat.parse("2019-09-12 15:00").getTime();
        long to = simpleFormat.parse(toStr).getTime();
        int days = (int) ((to - from)/(1000 * 60 * 60 * 24));
        System.out.println(days);
    }
}
